package com.ikkong.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.json.JSONArray;
import org.json.JSONObject;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ikkong.common.util.CommonUtils;
import com.ikkong.common.util.FileUtil;
import com.ikkong.common.util.OCRUtil;
import com.ikkong.core.constant.Cst;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.dao.Db;
import com.ikkong.core.toolbox.Func;
import com.ikkong.core.toolbox.Record;
import com.ikkong.platform.model.AppVersion;
import com.ikkong.platform.model.BaiduAccount;
import com.ikkong.platform.model.BankBussiness;
import com.ikkong.platform.model.BaseDocument;
import com.ikkong.platform.model.Member;
import com.ikkong.platform.model.MemberDocument;
import com.ikkong.platform.model.Template;
import com.ikkong.platform.model.TemplateAttr;
import com.ikkong.platform.model.UserDocument;
import com.ikkong.platform.model.UserDocumentImage;
import com.ikkong.platform.model.UserInfo;
import com.ikkong.platform.service.BaseDocumentService;
import com.ikkong.platform.service.MemberDocumentService;
import com.ikkong.platform.service.UserDocumentService;
import com.ikkong.platform.service.impl.BaseDocumentServiceImpl;
import com.ikkong.platform.service.impl.MemberDocumentServiceImpl;
import com.ikkong.platform.service.impl.UserDocumentServiceImpl;
import com.ikkong.api.intercept.CommonInterceptor;
import com.ikkong.api.intercept.TokenInterceptor;
import com.ikkong.api.model.BaseResponse;
import com.ikkong.api.model.Code;
import com.ikkong.api.model.DataResponse;
import com.ikkong.api.model.DatumResponse;
import com.ikkong.api.util.WordUtil;
import com.ikkong.common.util.AliyunOSSUtils;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfplugin.mail.MailKit;

@Before({ CommonInterceptor.class, TokenInterceptor.class })
public class CommonApiController extends BaseAPIController {
	UserDocumentService userDocumentService = new UserDocumentServiceImpl();
	BaseDocumentService baseDocumentService = new BaseDocumentServiceImpl();
	MemberDocumentService memberDocumentService = new MemberDocumentServiceImpl();

	/**
	 * 提交识别图片 参数: 1.token 签名 2:imageData 图片数据（base64位） 3.template_id 所属模板
	 * 4.user_id 所属用户文档
	 * demo路径:http://blog.csdn.net/qq_36410795/article/details/72652027
	 * ?locationNum=8&fps=1
	 * 
	 */
	@Before(POST.class)
	public void postOcrImg() {
		DatumResponse response = new DatumResponse();
		try {
			Member member = getUser();
			int user_id = getParaToInt("user_id", 0);
			String imageData = getPara("imageData");
			int template_id = getParaToInt("template_id", 0);
			if (imageData.isEmpty()) {
				renderFailed("您没有上传头像");
				return;
			}
			// 输出base64 数据,截取","之后的值进行转换
			String str = imageData.substring(imageData.indexOf(",") + 1);

			/*
			 * String basePath = getRequest().getSession().getServletContext()
			 * .getRealPath("/");
			 */
			int AllowImgFileSize = 4194304; // 上传图片最大值(单位字节)（ 4 M = 4194304 B ）
			if (AllowImgFileSize != 0 && AllowImgFileSize < str.length()) {
				renderFailed("上传失败，请上传不大于4M的图片！");
				System.out.println("上传失败,base64图片大小:" + str.length() + "\n");
				return;
			}

			String basePath = (Cst.me().isRemoteMode() ? "" : PathKit
					.getWebRootPath());
			String filename = System.currentTimeMillis() + "";
			String avatar = basePath + "\\upload\\ocr\\img\\" + filename
					+ ".jpg";
			boolean flag = CommonUtils.GenerateImage(str, avatar);

			if (flag) {
				Date now = new Date();
				String dir = "/upload\\ocr\\img\\";
				String newfile_url = dir + filename + ".docx";
				// 保存到数据库
				Blade userDocumentImageBlade = Blade
						.create(UserDocumentImage.class);
				UserDocumentImage userDocumentImage = userDocumentImageBlade
						.findFirstBy(
								"user_id=#{user_id}&&template_id=#{template_id}",
								Record.create().set("user_id", user_id)
										.set("template_id", template_id));
				if (userDocumentImage != null) {
					// 先删除图片
					String url = userDocumentImage.getPath();
					if (!StringUtils.isEmpty(url)) {
						String path = (Cst.me().isRemoteMode() ? "" : PathKit
								.getWebRootPath()) + url;
						File f = new File(path);
						if (!f.exists()) {
							f.delete();
						}
					}
					userDocumentImage.setPath(newfile_url);
					userDocumentImage.setModifyTime(now);
					userDocumentImage.setMark(null);
					userDocumentImage.setStatus(1);
					userDocumentImageBlade.update(userDocumentImage);

				} else {
					// 新增图片
					UserDocumentImage newUserDocumentImage = new UserDocumentImage();
					newUserDocumentImage.setCreateTime(now);
					newUserDocumentImage.setMember_id(member.getId());
					newUserDocumentImage.setModifyTime(now);
					newUserDocumentImage.setPath(newfile_url);
					newUserDocumentImage.setStatus(1);
					newUserDocumentImage.setTemplate_id(template_id);
					newUserDocumentImage.setUser_id(user_id);
					userDocumentImageBlade.save(newUserDocumentImage);
				}

				response.setCode(Code.SUCCESS);
				response.setDatum(newfile_url);
				System.out.println("上传成功");
				renderJson(response);
				return;
			} else {
				renderFailed("上传失败");
				return;
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			renderError(e.getMessage());
		}
	}

	/**
	 * 获取模板图片 参数: 1.token 签名 2.user_id 所属用户文档
	 */
	@Before(POST.class)
	public void getTemplatesAndImgs() {
		DatumResponse response = new DatumResponse();
		try {
			// Member member = getUser();
			int user_id = getParaToInt("user_id", 0);
			Blade userDocumentBlade = Blade.create(UserDocument.class);

			UserDocument userDocument = userDocumentBlade.findFirstBy(
					"id=#{id}&&status!=3", Record.create().set("id", user_id));
			int bussiness_id = userDocument.getBussiness_id();

			Db dao = Db.init();
			String sql = "select t.id as template_id,t.`name`,t.category_id as tempType_id,t.bank_id,i.path,i.`status`,i.mark from tb_template t "
					+ " left join (select id,path,`status`,mark,template_id from tb_user_document_image where user_id=2) i  on template_id=i.template_id";
			sql += " where t.status=2&&t.bussiness_id=#{bussiness_id}";

			List<Record> data = dao.selectList(
					sql,
					Record.create().set("bussiness_id", bussiness_id)
							.set("user_id", user_id));

			/*
			 * List<UserDocumentImage> userDocumentImages =
			 * userDocumentImageBlade .findBy("user_id=#{user_id}",
			 * Record.create().set("user_id", user_id));
			 */

			response.setCode(Code.SUCCESS);
			response.setDatum(data);
			renderJson(response);

		} catch (Exception e) {
			System.out.println(e.getMessage());
			renderError(e.getMessage());
		}
	}

	/**
	 * 获取进度 参数: 1.token 签名 4.user_id 所属用户文档
	 * 
	 */
	@Before(POST.class)
	public void getProgress() {
		DatumResponse response = new DatumResponse();
		try {
			Member member = getUser();
			int user_id = getParaToInt("user_id", 0);
			Blade userDocumentBlade = Blade.create(UserDocument.class);
			UserDocument userDocument = userDocumentBlade.findFirstBy(
					"id=#{id}&&status!=3", Record.create().set("id", user_id));
			int bussiness_id = userDocument.getBussiness_id();

			Db dao = Db.init();
			String sql = "select t.id as template_id,t.`name`,t.category_id as tempType_id,t.bank_id from tb_template t ";
			sql += " where t.status=2&&t.bussiness_id=#{bussiness_id}";

			List<Record> data = dao.selectList(
					sql,
					Record.create().set("bussiness_id", bussiness_id)
							.set("user_id", user_id));

			int totalLength = data.size();
			Blade userDocumentImageBlade = Blade
					.create(UserDocumentImage.class);
			List<UserDocumentImage> userDocumentImages = userDocumentImageBlade
					.findBy("id", "user_id=#{user_id}&&status=2", Record
							.create().set("user_id", user_id));
			int passLength = userDocumentImages.size();

			NumberFormat numberFormat = NumberFormat.getInstance();
			// 设置精确到小数点后2位
			numberFormat.setMaximumFractionDigits(2);
			String result = numberFormat.format((float) passLength
					/ (float) totalLength * 100);
			response.setCode(Code.SUCCESS);
			response.setDatum(result);
			renderJson(response);

			/*
			 * int passLength=0;
			 * 
			 * for(UserDocumentImage image : userDocumentImages){
			 * if(image.getStatus()==1){ //未识别 }else if(image.getStatus()==2){
			 * //识别通过 passLength=passLength+1; }else if(image.getStatus()==3){
			 * //识别错误 } }
			 */

		} catch (Exception e) {
			System.out.println(e.getMessage());
			renderError(e.getMessage());
		}

	}

	/**
	 * 获取所属模板类型
	 * */
	@Before(POST.class)
	@Clear(TokenInterceptor.class)
	public void getTempTypes() {
		DataResponse response = new DataResponse();
		try {
			Db dao = Db.init();

			List<Record> dict = dao
					.selectList(
							"select num as tempType_id,name from tfw_dict where code=#{code}&& num<>0",
							Record.create().set("code", 920));

			if (dict.size() == 0) {
				response.setCode(Code.SUCCESS);
				response.setMessage("模板类型不存在");
				renderJson(response);
				return;
			}

			response.setCode(Code.SUCCESS);
			response.setMessage(null);
			response.setData(dict);
			renderJson(response);
		} catch (Exception e) {
			response.setCode(Code.ERROR);
			response.setMessage(e.getMessage());
			renderJson(response);
		}

	}

	/**
	 * 获取所属银行
	 * */
	@Before(POST.class)
	@Clear(TokenInterceptor.class)
	public void getBanks() {
		DataResponse response = new DataResponse();
		try {
			Db dao = Db.init();

			List<Record> dict = dao
					.selectList(
							"select num as brank_id,name from tfw_dict where code=#{code}&& num<>0",
							Record.create().set("code", 910));

			if (dict.size() == 0) {
				response.setCode(Code.SUCCESS);
				response.setMessage("银行不存在");
				renderJson(response);
				return;
			}

			response.setCode(Code.SUCCESS);
			response.setMessage(null);
			response.setData(dict);
			renderJson(response);
		} catch (Exception e) {
			response.setCode(Code.ERROR);
			response.setMessage(e.getMessage());
			renderJson(response);
		}

	}

	/**
	 * 获取所属银行业务模板
	 * */
	@Before(POST.class)
	// @Clear(TokenInterceptor.class)
	public void getBankBussinessList() {
		Member member = getUser();
		DataResponse response = new DataResponse();
		try {
			Db dao = Db.init();
			int type = getParaToInt("type", 0);
			if (type == 0) {
				renderJson(new BaseResponse(Code.FAIL, "type参数未传入"));
				return;
			}
			int bank_id = member.getBank_id();
			String sql = "select id as bussiness_id,name,status,createTime from tb_bank_bussiness where ";
			if (type == 1) {
				sql += "  status!=3";
			} else {
				sql += "  status=2";
			}
			if (bank_id != 0) {
				sql += " && bank_id=#{bank_id}";
			}

			List<Record> bussinessList = dao.selectList(sql, Record.create()
					.set("bank_id", bank_id));

			if (bussinessList.size() == 0) {
				response.setCode(Code.SUCCESS);
				response.setMessage("银行不存在");
				renderJson(response);
				return;
			}

			response.setCode(Code.SUCCESS);
			response.setMessage(null);
			response.setData(bussinessList);
			renderJson(response);
		} catch (Exception e) {
			response.setCode(Code.ERROR);
			response.setMessage(e.getMessage());
			renderJson(response);
		}

	}

	/**
	 * 获取所属模板
	 * 
	 * 参数：1.所属银行业务 bussiness_id
	 * */
	@Before(POST.class)
	// @Clear(TokenInterceptor.class)
	public void getTemplates() {
		Member member = getUser();
		DatumResponse response = new DatumResponse();
		int bank_id = member.getBank_id();
		int bussiness_id = getParaToInt("bussiness_id", 0);
		int user_id = getParaToInt("user_id", 0);

		// int template_id = getParaToInt("template_id", 0);
		try {

			if (bussiness_id == 0) {
				renderJson(new BaseResponse(Code.ARGUMENT_ERROR,
						"bussiness_id参数未传入"));
				return;
			}
			Blade bankBussinessBlade = Blade.create(BankBussiness.class);
			if (bank_id == 0) {
				BankBussiness bankBussiness = bankBussinessBlade
						.findById(bussiness_id);
				bank_id = bankBussiness.getBank_id();
			}

			Map<String, Object> data = new HashMap<String, Object>();
			Blade userDocumentBlade = Blade.create(UserDocument.class);
			Record userDocument = userDocumentBlade.findOneColBy("id,name",
					"id=#{id}&&status!=3", Record.create().set("id", user_id));
			if (userDocument != null) {
				data.put("userDocument", userDocument);
			}
			Db dao = Db.init();
			String sql = "select id,name,category_id as tempType_id,bank_id from tb_template where status=2 ";
			if (bank_id != 0) {
				sql += " && bank_id=#{bank_id}";
			}
			sql += " &&bussiness_id=#{bussiness_id} ";

			List<Record> templates = dao.selectList(
					sql,
					Record.create().set("bank_id", bank_id)
							.set("bussiness_id", bussiness_id));

			if (templates.size() == 0) {
				response.setCode(Code.SUCCESS);
				response.setMessage("所属模板不存在");
				renderJson(response);
				return;
			}
			data.put("templates", templates);

			response.setCode(Code.SUCCESS);
			response.setMessage(null);
			response.setDatum(data);
			renderJson(response);
		} catch (Exception e) {
			response.setCode(Code.ERROR);
			response.setMessage(e.getMessage());
			renderJson(response);
		}

	}

	/**
	 * 上传空白文档 path
	 * */
	@Before(POST.class)
	public void SaveEmptyDocument() {
		Member member = getUser();

	}

	/**
	 * 用户建档
	 * */
	@Before(POST.class)
	@Clear(TokenInterceptor.class)
	public void createUserDocument() {
		Member member = getUser();
		DatumResponse response = new DatumResponse();
		try {
			int bank_id = member.getBank_id();
			int bussiness_id = getParaToInt("bussiness_id", 0);
			int member_id = member.getId();
			if (bussiness_id == 0) {
				renderJson(new BaseResponse(Code.ARGUMENT_ERROR,
						"bussiness_id参数未传入"));
				return;
			}
			String content = null;
			int base_document_id = 0;
			int op_type = 2;
			if (bank_id != 0) {
				// 工作人员
				Blade BaseDocumentBlade = Blade.create(BaseDocument.class);
				BaseDocument baseDocument = BaseDocumentBlade.findFirstBy(
						"bank_id=#{bank_id}&&bussiness_id=#{bussiness_id}",
						Record.create().set("bank_id", bank_id)
								.set("bussiness_id", bussiness_id));
				if (baseDocument != null) {
					content = baseDocument.getContent();
					base_document_id = baseDocument.getId();
				} else {
					response.setCode(Code.FAIL);
					response.setMessage("请先上传该模板的空白手册");
					renderJson(response);
					return;
				}
				op_type = 2;
			} else {
				// 普通用户
				Blade memberDocumentBlade = Blade.create(MemberDocument.class);
				MemberDocument memberDocument = memberDocumentBlade
						.findFirstBy("member_id=#{member_id}&&bussiness_id=#{bussiness_id}", Record.create()
								.set("member_id", member_id).set("bussiness_id", bussiness_id));
				if (memberDocument != null) {
					content = memberDocument.getContent();
					base_document_id = memberDocument.getId();
				} else {
					response.setCode(Code.FAIL);
					response.setMessage("请先上传您的空白手册");
					renderJson(response);
					return;
				}
				op_type = 1;
			}
			Blade bankBussinessBlade = Blade.create(BankBussiness.class);
			if (bank_id == 0) {
				BankBussiness bankBussiness = bankBussinessBlade
						.findById(bussiness_id);
				bank_id = bankBussiness.getBank_id();
			}
			String name = getPara("name");
			Blade userDocumentBlade = Blade.create(UserDocument.class);
			UserDocument userDocument = new UserDocument();
			userDocument.setBank_id(bank_id);
			userDocument.setName(name);
			userDocument.setMember_id(member_id);
			Date now = new Date();
			userDocument.setCreateTime(now);
			userDocument.setModifyTime(now);
			userDocument.setStatus(1);
			userDocument.setMark(content);
			userDocument.setBussiness_id(bussiness_id);
			userDocument.setBase_document_id(base_document_id);
			userDocument.setType(op_type);
			int id = userDocumentBlade.saveRtId(userDocument);
			response.setCode(Code.SUCCESS);
			response.setMessage(null);
			response.setDatum(id);
			renderJson(response);
		} catch (Exception e) {
			response.setCode(Code.ERROR);
			response.setMessage(e.getMessage());
			renderJson(response);
		}

	}

	/**
	 * 获取某个银行下的用户资料档(如果是个人用户，获取自己的用户资料；如果是银行人员，获取客户资料)
	 * */
	@Before(POST.class)
	// @Clear(TokenInterceptor.class)
	public void getUserDocuments() {
		Member member = getUser();
		DataResponse response = new DataResponse();
		try {
			int member_id = member.getId();
			String keyword = getPara("keyword");
			Blade userDocumentBlade = Blade.create(UserDocument.class);
			Db dao = Db.init();
			String sql = "select * from tb_user_document where member_id=#{member_id}&&status!=3 ";

			if (StringUtils.isNotEmpty(keyword)) {
				sql += "&&name like #{keyword}";
			}
			sql+=" ORDER BY createTime desc";
			List<Record> userDocs = dao.selectList(
					sql,
					Record.create().set("member_id", member_id)
							.set("keyword", "%" + keyword + "%"));

			response.setCode(Code.SUCCESS);
			response.setMessage(null);
			response.setData(userDocs);
			renderJson(response);
		} catch (Exception e) {
			response.setCode(Code.ERROR);
			response.setMessage(e.getMessage());
			renderJson(response);
		}

	}

	/**
	 * 提交用户资料
	 * */
	@Before(POST.class)
	public void PostUserInfos_new() {
		Member member = getUser();
		DataResponse response = new DataResponse();
		try {
			int bank_id = member.getBank_id();
			int user_id = getParaToInt("user_id", 0);
			int bussiness_id = getParaToInt("bussiness_id", 0);
			String imageDatas = getPara("imageDatas");

			if (bussiness_id == 0) {
				response.setCode(Code.FAIL);
				response.setMessage("bussiness_id参数未传入");
				renderJson(response);
				return;
			}

			if (imageDatas.isEmpty()) {
				response.setCode(Code.FAIL);
				response.setMessage("未上传图片");
				renderJson(response);
				return;
			}

			net.sf.json.JSONArray imgData_jsonArr = net.sf.json.JSONArray
					.fromObject(imageDatas);
			List<String> paths = new ArrayList<String>();
			int i = 0;
			for (Object imgData_json : imgData_jsonArr) {
				System.out.println(imgData_json);
				if (imgData_json == null) {
					response.setCode(Code.FAIL);
					response.setMessage("第" + (i + 1) + "张图片丢失，请重新上传");
					renderJson(response);
					return;
				} else {
					net.sf.json.JSONObject imgObj = net.sf.json.JSONObject
							.fromObject(imgData_json);
					String path = (Cst.me().isRemoteMode() ? "" : PathKit
							.getWebRootPath()) + imgObj.getString("path");
					File f = new File(path);
					if (!f.exists()) {
						response.setCode(Code.FAIL);
						response.setMessage("第" + (i + 1) + "张图片不存在，请重新上传");
						renderJson(response);
						return;
					}

					paths.add(imgObj.getString("path"));

				}
				i++;
			}

			// 初始化一个AipOcr
			Blade baiduAccountBlade = Blade.create(BaiduAccount.class);
			Blade templateAttrBlade = Blade.create(TemplateAttr.class);
			Blade templateBlade = Blade.create(Template.class);
			Blade bankBussinessBlade = Blade.create(BankBussiness.class);
			Blade userDocumentImageBlade = Blade
					.create(UserDocumentImage.class);
			if (bank_id == 0) {
				BankBussiness bankBussiness = bankBussinessBlade
						.findById(bussiness_id);
				if (bankBussiness != null) {
					bank_id = bankBussiness.getBank_id();
				}
			}

			Blade userDocumentBlade = Blade.create(UserDocument.class);
			BaiduAccount baiduAccount = baiduAccountBlade.findFirstBy(
					"id=#{id}", Record.create().set("id", 1));
			if (baiduAccount == null) {
				response.setCode(Code.FAIL);
				response.setMessage("百度账号不存在");
				renderJson(response);
				return;
			}
			String appId = baiduAccount.getAppId();
			String appKey = baiduAccount.getApiKey();
			String secretKey = baiduAccount.getSecretKey();
			String accessToken = OCRUtil.getBaiduAccessToken();
			AipOcr client = new AipOcr(appId, appKey, secretKey);
			// 传入可选参数调用接口
			HashMap<String, String> options = new HashMap<String, String>();
			JSONObject res = null;
			// 获取模板属性（即占位符字段）
			String templateAttrSql = "bussiness_id=#{bussiness_id}&&bank_id=#{bank_id}&&status=1";
			List<TemplateAttr> templateAttrs = templateAttrBlade.findBy(
					templateAttrSql,
					Record.create().set("bussiness_id", bussiness_id)
							.set("bank_id", bank_id));
			if (templateAttrs.size() == 0) {
				response.setCode(Code.FAIL);
				response.setMessage("请在后台补充占位符");
				renderJson(response);
				return;
			}

			// 模版不存在
			List<Template> templateList = templateBlade.findBy(
					"bussiness_id=#{bussiness_id}",
					Record.create().set("bussiness_id", bussiness_id));
			if (templateList == null) {
				response.setCode(Code.FAIL);
				response.setMessage("请在后台添加模版");
				renderJson(response);
				return;
			}

			// boolean flag2 = true;
			String errMsg = "";
			int j = 0;
			for (Object imgData_json : imgData_jsonArr) {
				net.sf.json.JSONObject imgObj = net.sf.json.JSONObject
						.fromObject(imgData_json);
				int tempType_id = imgObj.getInt("tempType_id");
				int template_id = imgObj.getInt("template_id");
				String path = (Cst.me().isRemoteMode() ? "" : PathKit
						.getWebRootPath()) + imgObj.getString("path");

				List<TemplateAttr> imgTemplateAttrs = new ArrayList<TemplateAttr>();
				for (TemplateAttr templateAttr : templateAttrs) {
					if (templateAttr.getTemplate_id() == template_id) {
						imgTemplateAttrs.add(templateAttr);
					}
				}
				if (imgTemplateAttrs.size() == 0) {
					System.out.println("第" + (j + 1) + "张图片,请在后台补充占位符");
					// flag2 = false;
					errMsg += "第" + (j + 1) + "张图片,请在后台补充占位符;";
					continue;
				}

				if (tempType_id == 1) {
					// 通用文字识别
					res = client.basicGeneral(path, options);
				} else if (tempType_id == 2) {
					// 通用文字识别(高精度版)
					res = client.basicAccurateGeneral(path, options);
				} else if (tempType_id == 3) {
					// 通用文字识别(含位置信息版)
					res = client.general(path, options);
				} else if (tempType_id == 4) {
					// 通用文字识别(含位置高精度版)
					res = client.accurateGeneral(path, options);
				} else if (tempType_id == 5) {
					// 通用文字识别(含生僻字版)
					res = client.enhancedGeneral(path, options);
				} else if (tempType_id == 6) {
					// 网络图片文字识别
					res = client.webImage(path, options);
				} else if (tempType_id == 7) {
					// 手写文字识别
					res = client.handwriting(path, options);
				} else if (tempType_id == 8) {
					// 身份证识别
					// front：身份证含照片的一面；back：身份证带国徽的一面
					options.put("detect_direction", "true");
					options.put("detect_risk", "true");
					String idCardSide = "front";

					System.out.println("调用百度识别开始。。。。。。。");
					try {
						res = client.idcard(path, idCardSide, options);
					} catch (Exception ex) {
						String msg = "第" + (j + 1) + "张图片,百度识别异常;";
						System.out.println(msg);
						errMsg += msg;
						modifyBaiduOcrState(user_id, template_id, false, msg,
								userDocumentImageBlade);
						continue;
					}
					System.out.println(res);
					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject words_result = res.getJSONObject("words_result");
					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						JSONObject attr = words_result
								.getJSONObject(templateAttr.getCname());
						String value = attr.getString("words");

						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 9) {
					// 银行卡识别
					System.out.println("调用百度识别开始。。。。。。。");
					try {
						res = client.bankcard(path, options);
					} catch (Exception ex) {
						String msg = "第" + (j + 1) + "张图片,百度识别异常;";
						System.out.println(msg);
						errMsg += msg;
						modifyBaiduOcrState(user_id, template_id, false, msg,
								userDocumentImageBlade);
						continue;
					}
					System.out.println(res);
					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject words_result = res.getJSONObject("result");
					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						String value = words_result.getString(templateAttr
								.getCname());
						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 10) {
					// 驾驶证识别
					System.out.println("调用百度识别开始。。。。。。。");
					try {
						res = client.drivingLicense(path, options);
					} catch (Exception ex) {
						String msg = "第" + (j + 1) + "张图片,百度识别异常;";
						System.out.println(msg);
						errMsg += msg;
						modifyBaiduOcrState(user_id, template_id, false, msg,
								userDocumentImageBlade);
						continue;
					}
					System.out.println(res);

					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject data = res.getJSONObject("data");
					JSONObject words_result = data
							.getJSONObject("words_result");

					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						JSONObject attr = words_result
								.getJSONObject(templateAttr.getCname());
						String value = attr.getString("words");
						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 11) {
					// 行驶证识别
					System.out.println("调用百度识别开始。。。。。。。");
					try {
						res = client.vehicleLicense(path, options);
					} catch (Exception ex) {
						String msg = "第" + (j + 1) + "张图片,百度识别异常;";
						System.out.println(msg);
						errMsg += msg;
						modifyBaiduOcrState(user_id, template_id, false, msg,
								userDocumentImageBlade);
						continue;
					}
					System.out.println(res);
					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject data = res.getJSONObject("data");
					JSONObject words_result = data
							.getJSONObject("words_result");

					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						JSONObject attr = words_result
								.getJSONObject(templateAttr.getCname());
						String value = attr.getString("words");
						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 12) {
					// 车牌识别

					System.out.println("调用百度识别开始。。。。。。。");
					try {
						res = client.plateLicense(path, options);
					} catch (Exception ex) {

						String msg = "第" + (j + 1) + "张图片,百度识别异常;";
						System.out.println(msg);
						errMsg += msg;
						modifyBaiduOcrState(user_id, template_id, false, msg,
								userDocumentImageBlade);
						continue;
					}
					System.out.println(res);
					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject words_result = res.getJSONObject("words_result");
					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						String value = words_result.getString(templateAttr
								.getCname());
						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 13) {
					// 营业执照识别

					System.out.println("调用百度识别开始。。。。。。。");
					try {
						res = client.businessLicense(path, options);
					} catch (Exception ex) {
						String msg = "第" + (j + 1) + "张图片,百度识别异常;";
						System.out.println(msg);
						errMsg += msg;
						modifyBaiduOcrState(user_id, template_id, false, msg,
								userDocumentImageBlade);
						continue;
					}
					System.out.println(res);

					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject words_result = res.getJSONObject("words_result");
					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						JSONObject attr = words_result
								.getJSONObject(templateAttr.getCname());
						String value = attr.getString("words");
						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 14) {
					// 护照识别
					res = client.passport(path, options);
				} else if (tempType_id == 15) {
					// 名片识别
					res = client.businessCard(path, options);
				} else if (tempType_id == 16) {
					// 表格文字识别(异步接口)
					// res=client.f
				} else if (tempType_id == 17) {
					// 表格文字识别(同步接口)
				} else if (tempType_id == 18) {
					// 通用票据识别
					res = client.receipt(path, options);
				} else if (tempType_id == 19) {
					// 增值税发票识别
					res = client.vatInvoice(path, options);
				} else if (tempType_id == 20) {
					// 二维码识别
					res = client.qrcode(path, options);
				} else if (tempType_id == 21) {
					// 数字识别
					res = client.numbers(path, options);
				} else if (tempType_id == 22) {
					// 彩票识别
					res = client.lottery(path, options);
				} else if (tempType_id == 23) {
					// 自定义模版文字识别
					Template template = null;
					for (Template t : templateList) {
						if (t.getCategory_id() == tempType_id
								&& t.getBank_id() == bank_id
								&& t.getId() == template_id) {
							template = t;
						}
					}
					if (template == null) {
						String msg = "第" + (j + 1)
								+ "张图片,模板不存在，请在后台添加与百度一致的模板;";
						System.out.println(msg);
						errMsg += msg;
						modifyBaiduOcrState(user_id, template_id, false, msg,
								userDocumentImageBlade);
						continue;
					}

					String tempSign = template.getTemplateSign();
					System.out.println("调用百度识别开始。。。。。。。");
					try {
						res = client.custom(path, tempSign, options);
					} catch (Exception ex) {
						String msg = "第" + (j + 1) + "张图片,百度识别异常;";
						System.out.println(msg);
						errMsg += msg;
						modifyBaiduOcrState(user_id, template_id, false, msg,
								userDocumentImageBlade);
						continue;
					}
					System.out.println(res);
					int error_code = res.getInt("error_code");
					if (error_code == 0) {
						// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
						JSONObject data = res.getJSONObject("data");
						// 模板id
						// String data_templateSign
						// =data.getString("templateSign");
						// 表示是否结构话成功
						boolean data_isStructured = data
								.getBoolean("isStructured"); // 调用的日志id
						if (data_isStructured) {
							JSONArray data_ret = data.getJSONArray("ret");
							for (Object obj : data_ret) {
								JsonObject json = (JsonObject) new JsonParser()
										.parse(obj.toString());
								String word_name = json.get("word_name")
										.getAsString();
								String word = json.get("word").getAsString();
								for (TemplateAttr templateAttr : imgTemplateAttrs) {
									if (templateAttr.getCname().equals(
											word_name)) {
										int template_attr_id = templateAttr
												.getId();
										boolean flag = SaveUserInfo(bank_id,
												user_id, bussiness_id,
												template_id, word,
												template_attr_id);
									}
								}
							}
						} else {
							String msg = "第"
									+ (j + 1)
									+ "张图片,表示是否结构话成功，true为成功，false为失败--成功时候，返回结构化的识别结果--失败时，如果能识别，返回类似通用文字识别的结果，如果不能识别，返回空;";
							System.out.println(msg);
							errMsg += msg;
							modifyBaiduOcrState(user_id, template_id, false,
									msg, userDocumentImageBlade);
							continue;
						}

					} else {
						String error_msg = res.getString("error_msg");
						String msg = "第"
								+ (j + 1)
								+ "百度无法识别,百度错误代码查看(https://ai.baidu.com/docs#/OCR-API/5de44382),错误代码："
								+ error_code + ",错误信息：" + error_msg + ";";
						System.out.println(msg);
						errMsg += msg;
						modifyBaiduOcrState(user_id, template_id, false, msg,
								userDocumentImageBlade);
						continue;
					}
				}
				j++;
			}

			// 状态：1.未识别；2.识别通过；3.识别错误
			List<UserDocumentImage> userDocumentImage = userDocumentImageBlade
					.findBy("id", "user_id=#{user_id}&&status=2", Record
							.create().set("user_id", user_id));
			if (templateList.size() == userDocumentImage.size()) {
				userDocumentBlade.updateBy(
						"status=#{status},modifyTime=#{modifyTime}",
						"id=#{user_id}",
						Record.create().set("status", 2)
								.set("modifyTime", new Date())
								.set("user_id", user_id));
			} else {
				userDocumentBlade.updateBy(
						"status=#{status},modifyTime=#{modifyTime}",
						"id=#{user_id}",
						Record.create().set("status", 1)
								.set("modifyTime", new Date())
								.set("user_id", user_id));
			}

			response.setCode(Code.SUCCESS);
			response.setMessage(errMsg);
			renderJson(response);
		} catch (Exception e) {
			System.out.println("失败:" + e.getMessage());
			response.setCode(Code.ERROR);
			response.setMessage(e.getMessage());
			renderJson(response);
		}
	}

	public void modifyBaiduOcrState(int user_id, int template_id, boolean flag,
			String errMsg, Blade userDocumentImageBlade) {
		if (userDocumentImageBlade == null) {
			userDocumentImageBlade = Blade.create(UserDocumentImage.class);
		}
		UserDocumentImage userDocumentImage = userDocumentImageBlade
				.findFirstBy(
						"user_id=#{user_id}&&template_id=#{template_id}",
						Record.create().set("user_id", user_id)
								.set("template_id", template_id));
		if (userDocumentImage != null) {
			userDocumentImage.setModifyTime(new Date());
			if (flag) {
				userDocumentImage.setStatus(2);
				userDocumentImage.setMark(null);
			} else {
				userDocumentImage.setStatus(3);
				userDocumentImage.setMark(errMsg);

			}
			userDocumentImageBlade.update(userDocumentImage);
		}
	}

	/**
	 * 提交用户资料
	 * */
	@Before(POST.class)
	public void PostUserInfos() {
		Member member = getUser();
		DataResponse response = new DataResponse();
		try {
			int bank_id = member.getBank_id();
			int user_id = getParaToInt("user_id", 0);
			int bussiness_id = getParaToInt("bussiness_id", 0);
			String imageDatas = getPara("imageDatas");

			if (bussiness_id == 0) {
				response.setCode(Code.FAIL);
				response.setMessage("bussiness_id参数未传入");
				renderJson(response);
				return;
			}

			if (imageDatas.isEmpty()) {
				response.setCode(Code.FAIL);
				response.setMessage("未上传图片");
				renderJson(response);
				return;
			}

			net.sf.json.JSONArray imgData_jsonArr = net.sf.json.JSONArray
					.fromObject(imageDatas);
			List<String> paths = new ArrayList<String>();
			int i = 0;
			for (Object imgData_json : imgData_jsonArr) {
				System.out.println(imgData_json);
				if (imgData_json == null) {
					response.setCode(Code.FAIL);
					response.setMessage("第" + (i + 1) + "张图片丢失，请重新上传");
					renderJson(response);
					return;
				} else {
					net.sf.json.JSONObject imgObj = net.sf.json.JSONObject
							.fromObject(imgData_json);
					String path = (Cst.me().isRemoteMode() ? "" : PathKit
							.getWebRootPath()) + imgObj.getString("path");
					File f = new File(path);
					if (!f.exists()) {
						response.setCode(Code.FAIL);
						response.setMessage("第" + (i + 1) + "张图片不存在，请重新上传");
						renderJson(response);
						return;
					}
					paths.add(imgObj.getString("path"));
				}
				i++;
			}

			// 图片数据
			/*
			 * String imageData = getPara("imageData"); if (imageData.isEmpty())
			 * { renderArgumentError("您没有上传头像"); return; } String dir =
			 * "ocr/upload/img/"; String path =
			 * AliyunOSSUtils.putObject(imageData, dir);
			 */
			// 初始化一个AipOcr
			Blade baiduAccountBlade = Blade.create(BaiduAccount.class);
			Blade templateAttrBlade = Blade.create(TemplateAttr.class);
			Blade templateBlade = Blade.create(Template.class);
			Blade bankBussinessBlade = Blade.create(BankBussiness.class);
			if (bank_id == 0) {
				BankBussiness bankBussiness = bankBussinessBlade
						.findById(bussiness_id);
				if (bankBussiness != null) {
					bank_id = bankBussiness.getBank_id();
				}
			}

		
			BaiduAccount baiduAccount = baiduAccountBlade.findFirstBy(
					"id=#{id}", Record.create().set("id", 1));
			if (baiduAccount == null) {
				response.setCode(Code.FAIL);
				response.setMessage("百度账号不存在");
				renderJson(response);
				return;
			}
			String appId = baiduAccount.getAppId();
			String appKey = baiduAccount.getApiKey();
			String secretKey = baiduAccount.getSecretKey();
			String accessToken = OCRUtil.getBaiduAccessToken();
			AipOcr client = new AipOcr(appId, appKey, secretKey);
			// 传入可选参数调用接口
			HashMap<String, String> options = new HashMap<String, String>();
			JSONObject res = null;
			// 获取模板属性（即占位符字段）
			String templateAttrSql = "bussiness_id=#{bussiness_id}&&bank_id=#{bank_id}&&status=1";
			List<TemplateAttr> templateAttrs = templateAttrBlade.findBy(
					templateAttrSql,
					Record.create().set("bussiness_id", bussiness_id)
							.set("bank_id", bank_id));
			if (templateAttrs.size() == 0) {
				response.setCode(Code.FAIL);
				response.setMessage("请在后台补充占位符");
				renderJson(response);
				return;
			}

			int j = 0;
			for (Object imgData_json : imgData_jsonArr) {
				net.sf.json.JSONObject imgObj = net.sf.json.JSONObject
						.fromObject(imgData_json);
				int tempType_id = imgObj.getInt("tempType_id");
				int template_id = imgObj.getInt("template_id");
				String path = (Cst.me().isRemoteMode() ? "" : PathKit
						.getWebRootPath()) + imgObj.getString("path");

				List<TemplateAttr> imgTemplateAttrs = new ArrayList<TemplateAttr>();
				for (TemplateAttr templateAttr : templateAttrs) {
					if (templateAttr.getTemplate_id() == template_id) {
						imgTemplateAttrs.add(templateAttr);
					}
				}
				if (imgTemplateAttrs.size() == 0) {
					response.setCode(Code.FAIL);
					response.setMessage("第" + (j + 1) + "张图片,请在后台补充占位符");
					renderJson(response);
					return;
				}

				if (tempType_id == 1) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 通用文字识别
					res = client.basicGeneral(path, options);
				} else if (tempType_id == 2) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 通用文字识别(高精度版)
					res = client.basicAccurateGeneral(path, options);
				} else if (tempType_id == 3) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 通用文字识别(含位置信息版)
					res = client.general(path, options);
				} else if (tempType_id == 4) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 通用文字识别(含位置高精度版)
					res = client.accurateGeneral(path, options);
				} else if (tempType_id == 5) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 通用文字识别(含生僻字版)
					res = client.enhancedGeneral(path, options);
				} else if (tempType_id == 6) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 网络图片文字识别
					res = client.webImage(path, options);
				} else if (tempType_id == 7) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 手写文字识别
					res = client.handwriting(path, options);
				} else if (tempType_id == 8) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 身份证识别
					// front：身份证含照片的一面；back：身份证带国徽的一面
					options.put("detect_direction", "true");
					options.put("detect_risk", "true");
					String idCardSide = "front";
					res = client.idcard(path, idCardSide, options);
					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject words_result = res.getJSONObject("words_result");
					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						JSONObject attr = words_result
								.getJSONObject(templateAttr.getCname());
						String value = attr.getString("words");

						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 9) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 银行卡识别
					res = client.bankcard(path, options);
					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject words_result = res.getJSONObject("result");
					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						String value = words_result.getString(templateAttr
								.getCname());
						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 10) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 驾驶证识别
					res = client.drivingLicense(path, options);
					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject data = res.getJSONObject("data");
					JSONObject words_result = data
							.getJSONObject("words_result");

					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						JSONObject attr = words_result
								.getJSONObject(templateAttr.getCname());
						String value = attr.getString("words");
						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 11) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 行驶证识别
					res = client.vehicleLicense(path, options);
					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject data = res.getJSONObject("data");
					JSONObject words_result = data
							.getJSONObject("words_result");

					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						JSONObject attr = words_result
								.getJSONObject(templateAttr.getCname());
						String value = attr.getString("words");
						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 12) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 车牌识别
					res = client.plateLicense(path, options);
					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject words_result = res.getJSONObject("words_result");
					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						String value = words_result.getString(templateAttr
								.getCname());
						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 13) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 营业执照识别
					res = client.businessLicense(path, options);
					// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
					JSONObject words_result = res.getJSONObject("words_result");
					for (TemplateAttr templateAttr : imgTemplateAttrs) {
						JSONObject attr = words_result
								.getJSONObject(templateAttr.getCname());
						String value = attr.getString("words");
						int template_attr_id = templateAttr.getId();
						boolean flag = SaveUserInfo(bank_id, user_id,
								bussiness_id, template_id, value,
								template_attr_id);
					}
				} else if (tempType_id == 14) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 护照识别
					res = client.passport(path, options);
				} else if (tempType_id == 15) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 名片识别
					res = client.businessCard(path, options);
				} else if (tempType_id == 16) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 表格文字识别(异步接口)
					// res=client.f
				} else if (tempType_id == 17) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 表格文字识别(同步接口)
				} else if (tempType_id == 18) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 通用票据识别
					res = client.receipt(path, options);
				} else if (tempType_id == 19) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 增值税发票识别
					res = client.vatInvoice(path, options);
				} else if (tempType_id == 20) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 二维码识别
					res = client.qrcode(path, options);
				} else if (tempType_id == 21) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 数字识别
					res = client.numbers(path, options);
				} else if (tempType_id == 22) {
					// path = "G:\\星爵\\图文识别\\微信图片_20180103095633.jpg";
					// 彩票识别
					res = client.lottery(path, options);
				} else if (tempType_id == 23) {
					// 自定义模版文字识别
					Template template = templateBlade
							.findFirstBy(
									"category_id=#{tempType_id}&&bank_id=#{bank_id}&&id=#{template_id}",
									Record.create()
											.set("tempType_id", tempType_id)
											.set("bank_id", bank_id)
											.set("template_id", template_id));
					if (template == null) {
						response.setCode(Code.FAIL);
						response.setMessage("第" + (j + 1)
								+ "张图片,模板不存在，请在后台添加与百度一致的模板;");
						renderJson(response);
						return;
					}
					String tempSign = template.getTemplateSign();
					System.out.println("调用百度识别开始。。。。。。。");
					try {
						res = client.custom(path, tempSign, options);
					} catch (Exception ex) {
						System.out.println("第" + (j + 1) + "张图片,百度识别异常"
								+ ex.getMessage());
						response.setCode(Code.FAIL);
						response.setMessage("第" + (j + 1) + "张图片,百度识别异常");
						renderJson(response);
						return;
					}
					System.out.println(res);
					int error_code = res.getInt("error_code");
					if (error_code == 0) {
						// 0代表成功，如果有错误码返回可以参考下方错误码列表排查问题
						JSONObject data = res.getJSONObject("data");
						// 模板id
						// String data_templateSign
						// =data.getString("templateSign");
						// 表示是否结构话成功
						boolean data_isStructured = data
								.getBoolean("isStructured"); // 调用的日志id
						if (data_isStructured) {
							JSONArray data_ret = data.getJSONArray("ret");
							for (Object obj : data_ret) {
								JsonObject json = (JsonObject) new JsonParser()
										.parse(obj.toString());
								String word_name = json.get("word_name")
										.getAsString();
								String word = json.get("word").getAsString();
								for (TemplateAttr templateAttr : imgTemplateAttrs) {
									if (templateAttr.getCname().equals(
											word_name)) {
										//数据类型(1.数字，2.文字)
										if(StringUtils.isEmpty(word)){
											if(templateAttr.getData_type()==1){
												word="0";
											}
										}
									
										int template_attr_id = templateAttr
												.getId();
										boolean flag = SaveUserInfo(bank_id,
												user_id, bussiness_id,
												template_id, word,
												template_attr_id);
									}
								}
							}
						} else {
							response.setCode(Code.FAIL);
							response.setMessage("第"
									+ (j + 1)
									+ "张图片,表示是否结构话成功，true为成功，false为失败；成功时候，返回结构化的识别结果；失败时，如果能识别，返回类似通用文字识别的结果，如果不能识别，返回空");
							renderJson(response);
							return;
						}

					} else {
						String error_msg = res.getString("error_msg");
						response.setCode(Code.FAIL);
						response.setMessage("第"
								+ (j + 1)
								+ "张图片，百度无法识别。百度错误代码查看(https://ai.baidu.com/docs#/OCR-API/5de44382);错误代码："
								+ error_code + ";错误信息：" + error_msg);
						renderJson(response);
						return;

					}
				}
				j++;
			}
			Blade userDocumentBlade = Blade.create(UserDocument.class);
			userDocumentBlade.updateBy(
					"status=#{status},modifyTime=#{modifyTime}",
					"id=#{user_id}",
					Record.create().set("status", 2)
							.set("modifyTime", new Date())
							.set("user_id", user_id));
			// System.out.println("图片使用完成");
			// 删除图片
			for (String p : paths) {
				File f = new File((Cst.me().isRemoteMode() ? ""
						: PathKit.getWebRootPath())
						+ p);
				if (f.exists()) {
					f.delete();
				}

			}
			System.out.println("删除已使用的图片");

			response.setCode(Code.SUCCESS);
			renderJson(response);
		} catch (Exception e) {
			System.out.println("失败:" + e.getMessage());
			response.setCode(Code.ERROR);
			response.setMessage(e.getMessage());
			renderJson(response);
		}
	}

	public boolean SaveUserInfo(int bank_id, int user_id, int bussiness_id,
			int template_id, String value, int template_attr_id) {
		try {
			Date now = new Date();
			Blade userInfoBlade = Blade.create(UserInfo.class);
			UserInfo oldUserInfo = userInfoBlade
					.findFirstBy(
							"user_id=#{user_id}&&bussiness_id=#{bussiness_id}&&template_id=#{template_id}&&template_attr_id=#{template_attr_id}",
							Record.create().set("user_id", user_id)
									.set("template_id", template_id)
									.set("template_attr_id", template_attr_id)
									.set("bussiness_id", bussiness_id));
			if (oldUserInfo != null) {
				if (!oldUserInfo.getValue().equals(value)) {
					userInfoBlade.updateBy(
							"value=#{value}",
							"id=#{id}",
							Record.create().set("value", value)
									.set("id", oldUserInfo.getId()));
				}
			} else {
				UserInfo us = new UserInfo();
				us.setUser_id(user_id);
				us.setCreateTime(now);
				us.setModifyTime(now);
				us.setTemplate_attr_id(template_attr_id);
				us.setTemplate_id(template_id);
				us.setBussiness_id(bussiness_id);
				us.setBank_id(bank_id);
				us.setValue(value);
				userInfoBlade.save(us);
			}
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		}
	}

	/**
	 * 发送邮件
	 * 
	 * https://blog.csdn.net/zsq520520/article/details/53538301
	 * */ 
	@Before(POST.class)
	// @Clear(TokenInterceptor.class)
	public void sendmail() {
		DataResponse response = new DataResponse();
		try {
			Member member = getUser();
			List<File> attachments = new ArrayList<File>();
			int user_id = getParaToInt("user_id", 0);
			String email = getPara("email");
			UserDocument userDocument = userDocumentService.findById(user_id);
			if (userDocument == null) {
				response.setCode(Code.FAIL);
				response.setMessage("用户没有相关文档，无法发送");
				renderJson(response);
				return;
			}
			String content = userDocument.getMark();
			Db dao = Db.init();
			List<Record> userInfos = dao
					.selectList(
							"select u.*,a.ename,a.cname from tb_user_info u "
							+ "left join (select id,ename,cname,'order',isMust from tb_template_attr ) a "
									+ "on u.template_attr_id=a.id where u.user_id=#{user_id}",
							Record.create().set("user_id", user_id));

			Map<String, Object> params = new HashMap<String, Object>();
			for (Record r : userInfos) {
				params.put(r.getStr("ename"), r.getStr("value"));
			}
			// int member_id = member.getId();
			String path = null;
			int base_document_id = userDocument.getBase_document_id();
			if (member.getBank_id() == 0) {
				MemberDocument memberDocument = memberDocumentService
						.findById(base_document_id);
				if (memberDocument == null) {
					response.setCode(Code.FAIL);
					response.setMessage("空白手册不存在，请让管理员在后台上传空白手册");
					renderJson(response);
					return;
				}
				path = memberDocument.getPath();
			} else {
				BaseDocument baseDocument = baseDocumentService
						.findById(base_document_id);
				if (baseDocument == null) {
					response.setCode(Code.FAIL);
					response.setMessage("空白手册不存在，请让管理员在后台上传空白手册");
					renderJson(response);
					return;
				}
				path = baseDocument.getPath();
			}

			Map<String, Object> file = Db.init().findById("TFW_ATTACH", path);
			String filePath = null;
			if (Func.isEmpty(file)) {
				response.setCode(Code.FAIL);
				response.setMessage("模板不存在，请先上传模板");
				renderJson(response);
				return;
			} else {
				String url = file.get("URL").toString();
				filePath = (Cst.me().isRemoteMode() ? "" : PathKit
						.getWebRootPath()) + url;
			}
			if (filePath.isEmpty()) {
				response.setCode(Code.FAIL);
				response.setMessage("模板不存在，请先上传模板");
				renderJson(response);
				return;
			}
			InputStream is = new FileInputStream(filePath);
			System.out.println("读取模板");
			// 替换段落里面的变量
			System.out.println(JSONUtils.toJSONString(params));
			String basePath = (Cst.me().isRemoteMode() ? "" : PathKit
					.getWebRootPath());
			String dir = "/upload\\ocr\\document\\";
			String filename = userDocument.getName();
			String titlename = System.currentTimeMillis() + "";
			String newfile_url = basePath + dir + titlename + ".docx";
			
			if(filePath.endsWith("doc")){
				response.setCode(Code.FAIL);
				response.setMessage("您上传的空白手册模板格式不正确");
				renderJson(response);
				return;
			}else if(filePath.endsWith("docx")){
				XWPFDocument doc = new XWPFDocument(is);
				WordUtil.replaceInPara(doc, params);
				// 替换表格里面的变量
				WordUtil.replaceInTable(doc, params);
				
				// 替换表格里面的变量
				WordUtil.replaceText(doc, params);
				System.out.println("替换模板中的占位符");
				
				OutputStream os = new FileOutputStream(newfile_url);
				doc.write(os);
				WordUtil.close(os);
				WordUtil.close(is);
			}else{
				response.setCode(Code.FAIL);
				response.setMessage("您上传的空白手册模板格式不正确");
				renderJson(response);
				return;
			}
		
			

			File f = new File(newfile_url);
			attachments.add(f);
			MailKit.send(email, null, filename, "邮件内容", attachments);
			System.out.println("成功");
			if (f.exists()) {
				f.delete();
			}
			response.setCode(Code.SUCCESS);
			renderJson(response);
		} catch (Exception e) {
			System.out.println("失败:" + e.getMessage());
			response.setCode(Code.ERROR);
			response.setMessage(e.getMessage());
			renderJson(response);
		}

	}

	/**
	 * 获取最新版本信息
	 * */
	@Before(POST.class)
	@Clear(TokenInterceptor.class)
	public void getAppVersion() {
		DatumResponse response = new DatumResponse();
		try {

			String app_version = getPara("app_version");

			Blade appVersionBlade = Blade.create(AppVersion.class);
			AppVersion appVersion = appVersionBlade.findFirst(
					"select * from tb_app_version order by create_time desc",
					null);
			if (appVersion == null) {
				response.setCode(Code.ERROR);
				response.setMessage("未获取到版本信息");
				renderJson(response);
				return;
			}
			// 比较版本号的大小,前者大则返回一个正数,后者大返回一个负数,相等则返回0
			int code = CommonUtils.compareVersion(app_version,
					appVersion.getApp_version());
			if (code > 0) {
				// 目前版本过高
				response.setCode(Code.ERROR);
				response.setMessage("目前版本过高");
				renderJson(response);
				return;
			} else if (code == 0) {
				// 安装版本已是最高版本
				response.setCode(Code.ERROR);
				response.setMessage("安装版本已是最高版本");
				renderJson(response);
				return;
			} else {
				// 安装版本过低
				Map<String, Object> file = Db.init().findById("TFW_ATTACH",
						appVersion.getWgt_url());
				String wgt_url = null;
				if (file != null) {
					String url = file.get("URL").toString();
					/*
					 * wgt_url = (Cst.me().isRemoteMode() ? "" : PathKit
					 * .getWebRootPath()) + url;
					 */
					wgt_url = url;
				}

				Map<String, Object> file2 = Db.init().findById("TFW_ATTACH",
						appVersion.getFile_url());
				String file_url = null;
				if (file2 != null) {
					String url2 = file2.get("URL").toString();
					/*
					 * wgt_url = (Cst.me().isRemoteMode() ? "" : PathKit
					 * .getWebRootPath()) + url;
					 */
					file_url = url2;
				}

				Map<String, String> data = new HashMap<String, String>();
				data.put("version", appVersion.getApp_version());
				data.put("wgt_url", wgt_url);
				data.put("file_url", file_url);
				// 安装版本已是最高版本
				response.setCode(Code.SUCCESS);
				response.setMessage("有新版本，请升级...");
				response.setDatum(data);
				renderJson(response);
				return;

			}
		} catch (Exception e) {
			response.setCode(Code.ERROR);
			response.setMessage(e.getMessage());
			renderJson(response);
		}
	}
}
